1 /* 2 * Copyright (C) 2006 The Guava Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.common.io; 18 19 import com.google.common.annotations.Beta; 20 import com.google.common.base.Preconditions; 21 22 import java.io.File; 23 import java.io.FilenameFilter; 24 import java.util.regex.Pattern; 25 import java.util.regex.PatternSyntaxException; 26 27 import javax.annotation.Nullable; 28 29 /** 30 * File name filter that only accepts files matching a regular expression. This 31 * class is thread-safe and immutable. 32 * 33 * @author Apple Chow 34 * @since 1.0 35 */ 36 @Beta 37 public final class PatternFilenameFilter implements FilenameFilter { 38 39 private final Pattern pattern; 40 41 /** 42 * Constructs a pattern file name filter object. 43 * @param patternStr the pattern string on which to filter file names 44 * 45 * @throws PatternSyntaxException if pattern compilation fails (runtime) 46 */ 47 public PatternFilenameFilter(String patternStr) { 48 this(Pattern.compile(patternStr)); 49 } 50 51 /** 52 * Constructs a pattern file name filter object. 53 * @param pattern the pattern on which to filter file names 54 */ 55 public PatternFilenameFilter(Pattern pattern) { 56 this.pattern = Preconditions.checkNotNull(pattern); 57 } 58 59 @Override public boolean accept(@Nullable File dir, String fileName) { 60 return pattern.matcher(fileName).matches(); 61 } 62 }